﻿Public Class TimePicker

    Private _isDateVisible As Boolean = True

    Public Property IsDateVisible As Boolean
        Get
            Return _isDateVisible
        End Get
        Set(ByVal value As Boolean)
            _isDateVisible = value
            If value = True Then
                [Date].Visibility = Visibility.Visible
            Else
                [Date].Visibility = Visibility.Hidden
            End If
        End Set
    End Property

    Private _isTimeVisible As Boolean = True

    Public Property IsTimeVisible As Boolean
        Get
            Return _isTimeVisible
        End Get
        Set(ByVal value As Boolean)
            _isTimeVisible = value
            If value = True Then
                TimeStackPanel.Visibility = Visibility.Visible
            Else
                TimeStackPanel.Visibility = Visibility.Hidden
            End If
        End Set
    End Property

    Private _selectedDate As DateTime = DateTime.MinValue

    Public Property SelectedDate As DateTime
        Get
            _selectedDate = GetDateValue()
            Return _selectedDate
        End Get
        Set(ByVal value As DateTime)
            _selectedDate = value
            [Date].SelectedDate = _selectedDate
            HourTextBox.Text = _selectedDate.Hour.ToString.PadLeft(2, "0"c)
            MinuteTextBox.Text = _selectedDate.Minute.ToString.PadLeft(2, "0"c)
            SecondTextBox.Text = _selectedDate.Second.ToString.PadLeft(2, "0"c)
        End Set
    End Property

    Public Sub New()
        InitializeComponent()
        [Date].FirstDayOfWeek = DayOfWeek.Monday
    End Sub

    Private Sub TimeField_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles SecondTextBox.GotFocus, MinuteTextBox.GotFocus, HourTextBox.GotFocus
        DirectCast(sender, TextBox).SelectAll()
    End Sub

    Private Function GetDateValue() As DateTime

        Dim BaseDate As DateTime = DateTime.MinValue
        If [Date].SelectedDate IsNot Nothing Then BaseDate = [Date].SelectedDate

        Dim HourValue, MinuteValue, SecondValue As Integer
        If HourTextBox IsNot Nothing Then Integer.TryParse(HourTextBox.Text, HourValue)
        If MinuteTextBox IsNot Nothing Then Integer.TryParse(MinuteTextBox.Text, MinuteValue)
        If SecondTextBox IsNot Nothing Then Integer.TryParse(SecondTextBox.Text, SecondValue)

        If HourValue < 0 Then HourValue = 0
        If MinuteValue < 0 Then MinuteValue = 0
        If SecondValue < 0 Then SecondValue = 0
        If HourValue > 23 Then HourValue = 23
        If MinuteValue > 59 Then MinuteValue = 59
        If SecondValue > 59 Then SecondValue = 59

        Return New DateTime(BaseDate.Year, BaseDate.Month, BaseDate.Day, HourValue, MinuteValue, SecondValue)

    End Function

End Class
